package com.thread.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.thread.utility.ThreadUtility;

/**
 Future的方法
 get方法：获取计算结果，如果结果没有出来会等待，阻断当前线程，可以指定等待多长时间，如果超时则会抛出异常
 cancel方法：取消方法，可能会取消失败，可以指定如果任务已经开始执行是否取消
 isDone方法：是否执行完毕，包括完成、被取消、抛出异常等等
 isCancelled方法：是否被取消
 */
public class FirstCallableTask implements Callable<Long>{
	private String name;
	private int second;
	public FirstCallableTask(String name,int second) {
		this.name = name;
		this.second = second;
	}
	@Override
	public Long call() throws Exception {
		System.out.println(name + " begin");
		ThreadUtility.sleep(second);
		return Thread.currentThread().getId();
	}
	
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService service = Executors.newFixedThreadPool(2);
		Future<Long> firstFuture = service.submit(new FirstCallableTask("firstFuture",5));
		Future<Long> secondFuture = service.submit(new FirstCallableTask("secondFuture",15));
		
		ThreadUtility.sleep(1);
		
		firstFuture.cancel(true);
		
		if(secondFuture.isDone()) {
			System.out.println(secondFuture.get());
		}
		
		//任务被取消、完成或者抛出异常，isDone也返回true
		if(firstFuture.isDone()) {
			System.out.println(firstFuture.get());
		}
		service.shutdown();
	}
}
